"use client";
import { useSession } from "next-auth/react";
import { useEffect } from "react";
import { useRouter } from "next/navigation";

const ProtectedRoute = ({ children }) => {
  const { data: session, status } = useSession();
  const router = useRouter();

  useEffect(() => {
    // 加载中不处理
    if (status === "loading") return;

    // 未登录则跳转到登录页
    if (!session) {
      router.push("/dashboard/login?redirect=" + router.asPath);
    }
  }, [session, status, router]);

  // 加载中显示loading
  if (status === "loading") {
    return <div>Loading...</div>;
  }

  // 已登录则显示内容
  return session ? children : null;
};

export default ProtectedRoute;